#include <iostream>
#include <cstring>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Comm.hpp"
#include "Protocol.hpp"

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage client_tcp server_ip server_port" << std::endl;
        return 1;
    }
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "socket fail!" << std::endl;
        return 2;
    }

    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(server_port);
    server_addr.sin_addr.s_addr = inet_addr(server_ip.c_str());

    // client不需要显示的bind，tcp是面向连接的，connect底层会自动bind
    int n = connect(sockfd, CONV(&server_addr), sizeof(server_addr));
    if (n < 0)
    {
        std::cout << "connect fail!" << std::endl;
        return 3;
    }

    std::string message;
    while (true)
    {
        int x, y;
        char oper;
        std::cout << "input x: ";
        std::cin >> x;
        std::cout << "input y: ";
        std::cin >> y;
        std::cout << "input oper: ";
        std::cin >> oper;

        // 1.构建请求
        Request req(x, y, oper);
        // 2.序列化
        req.Serialize(message);
        // 3.添加报头
        Encode(message);
        // 4.发送
        n = send(sockfd, message.c_str(), message.size(), 0);
        if (n > 0)
        {
            char inbuffer[1024];
            // 5.获得响应
            int m = recv(sockfd, inbuffer, sizeof(inbuffer), 0);
            if (m > 0)
            {
                inbuffer[m] = 0;
                std::string package = inbuffer;
                std::string content;
                // 6.去掉报头
                Decode(package, &content);
                // 7.反序列化
                Response res;
                res.Deserialize(content);

                std::cout << res.Result() << "[" << res.Code() << "]" << std::endl;
            }
            else break;
        }
        else break;
    }

    close(sockfd);
    return 0;
}